package me.szlx.thing.parser;

import me.szlx.thing.Thing;
import me.szlx.thing.Trait;
import me.szlx.thing.Traits;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

public class PropertiesThingParser<T extends Thing> extends AbstractThingParser<T> implements ThingParser<T> {
    @Override
    protected List<T> doParse(InputStream resource) {
        final Properties properties = new Properties();
        List<T> result = new ArrayList<>();
        try {
            properties.load(resource);
            return properties.stringPropertyNames().stream()
                    .filter(name -> getPrefix() == null || name.startsWith(getPrefix()))
                    .map(name -> getPrefix() == null ? name : name.substring(getPrefix().length()))
                    .filter(name -> !name.contains("."))
                    .map(name -> createThing(name, properties)).collect(Collectors.toList());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return result;
    }

    private T createThing(String code, Properties properties) {
        if (code == null || properties == null) {
            return null;
        }

        String theNameKey = getPrefix() == null ? code : getPrefix() + code;
        String theName = properties.getProperty(theNameKey);
        if (theName != null) {
            String theDescriptionKey = getPrefix() == null ? code + ".description" : getPrefix() + code + ".description";
            String theDescription = properties.getProperty(theDescriptionKey);

            String theTraitPrefix = getPrefix() == null ? code + ".traits." : getPrefix() + code + ".traits.";
            List<Trait> traitList = properties.stringPropertyNames().stream()
                    .filter(name -> name.startsWith(theTraitPrefix))
                    .map(name -> {
                        String traitName = name.substring(theTraitPrefix.length());
                        String traitValue = properties.getProperty(name);
                        return createTrait(traitName, traitValue);
                    }).collect(Collectors.toList());
            Traits theTraits = traitList.isEmpty() ? null : Traits.of(traitList);
            return createThing(code, theName, theDescription, theTraits);
        }
        logger.debug("事物名称不能为null，忽略 {}", code);
        return null;
    }
}
